package thread.nio.base;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 基于NIO的文件复制
 * 基本操作
 * 1.得到FileInputStream fin = new  FileInputStream(new File("..."));
 * 2.得到通道  FileChannel fc = fin.getChannel();
 * 3.设置缓冲 ByteBuffer byteBuffer =  ByteBuffer.allocate(1024);
 * 4.通过通道读取buffer
 * 5.关闭通道
 * 6.缓冲复位
 * 
 * 						
 */
public class CopyFile {

	public static void nioCopyFile(String resource, String dest) throws IOException {
		FileInputStream fis = new FileInputStream(resource);
		FileOutputStream fos = new FileOutputStream(dest);
		FileChannel readChannel = fis.getChannel();
		FileChannel writeChannel = fos.getChannel();
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		while (true) {
			byteBuffer.clear();
			int len = readChannel.read(byteBuffer);
			if (len == -1) {
				break; // 读取完毕
			}
			byteBuffer.flip();
			//写入文件
			writeChannel.write(byteBuffer);
		}
		readChannel.close();
		writeChannel.close();
	}
	
	public static void main(String[] args) {
		try {
			long start = System.currentTimeMillis();
			nioCopyFile("F:\\百度云\\ngrok.zip", "F:\\百度云\\n.zip");
			System.out.println("耗时:" + (System.currentTimeMillis() - start));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
